package com.example.foodwebbackend.controller;

import com.example.foodwebbackend.dto.ApiResponse;
import com.example.foodwebbackend.dto.MerchantRequest;
import com.example.foodwebbackend.dto.PageRequest;
import com.example.foodwebbackend.dto.PageResponse;
import com.example.foodwebbackend.entity.Merchant;
import com.example.foodwebbackend.service.MerchantService;
import com.example.foodwebbackend.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/admin/merchants")
@CrossOrigin(origins = "*")
public class AdminMerchantController {

    @Autowired
    private MerchantService merchantService;
    
    @Autowired
    private JwtUtil jwtUtil;

    /**
     * 分页获取商家列表
     */
    @GetMapping
    public ApiResponse<PageResponse<Merchant>> getMerchants(
        @RequestParam(defaultValue = "1") int page,
        @RequestParam(defaultValue = "20") int size,
        @RequestParam(required = false) String search,
        @RequestParam(required = false) Integer approvalStatus,
        @RequestHeader(value = "Authorization", required = false) String token
    ) {
        try {
            PageRequest pageRequest = new PageRequest(page, size, search, approvalStatus);
            PageResponse<Merchant> merchants = merchantService.getMerchantsWithPagination(pageRequest);
            return ApiResponse.success(merchants);
        } catch (Exception e) {
            return ApiResponse.error("获取商家列表失败: " + e.getMessage());
        }
    }

    /**
     * 根据ID获取商家详情
     */
    @GetMapping("/{id}")
    public ApiResponse<Merchant> getMerchantById(
        @PathVariable Integer id,
        @RequestHeader(value = "Authorization", required = false) String token
    ) {
        try {
            Merchant merchant = merchantService.findById(id);
            if (merchant == null) {
                return ApiResponse.error("商家不存在");
            }
            return ApiResponse.success(merchant);
        } catch (Exception e) {
            return ApiResponse.error("获取商家详情失败: " + e.getMessage());
        }
    }

    /**
     * 添加商家
     */
    @PostMapping
    public ApiResponse<Merchant> addMerchant(
        @RequestBody MerchantRequest request,
        @RequestHeader(value = "Authorization", required = false) String token
    ) {
        try {
            if (request.getUsername() == null || request.getPassword() == null || 
                request.getMerchantName() == null || request.getMerchantAddress() == null ||
                request.getContactPhone() == null) {
                return ApiResponse.error("商家基本信息不能为空");
            }
            
            if (request.getContactPhone().length() > 20) {
                return ApiResponse.error("联系电话不能超过20个字符");
            }
            
            if (merchantService.existsByUsername(request.getUsername())) {
                return ApiResponse.error("用户名已存在");
            }
            
            Merchant merchant = merchantService.createMerchant(request);
            return ApiResponse.success("商家添加成功", merchant);
        } catch (Exception e) {
            return ApiResponse.error("添加商家失败: " + e.getMessage());
        }
    }

    /**
     * 更新商家信息
     */
    @PutMapping("/{id}")
    public ApiResponse<Merchant> updateMerchant(
        @PathVariable Integer id,
        @RequestBody MerchantRequest request,
        @RequestHeader(value = "Authorization", required = false) String token
    ) {
        try {
            Merchant existingMerchant = merchantService.findById(id);
            if (existingMerchant == null) {
                return ApiResponse.error("商家不存在");
            }
            
            // 检查用户名是否已被其他商家使用
            if (request.getUsername() != null && 
                !request.getUsername().equals(existingMerchant.getUsername()) &&
                merchantService.existsByUsername(request.getUsername())) {
                return ApiResponse.error("用户名已存在");
            }
            
            // 验证电话号码长度（如果提供了电话号码）
            if (request.getContactPhone() != null && request.getContactPhone().length() > 20) {
                return ApiResponse.error("联系电话不能超过20个字符");
            }
            
            Merchant updatedMerchant = merchantService.updateMerchant(id, request);
            return ApiResponse.success("商家更新成功", updatedMerchant);
        } catch (Exception e) {
            return ApiResponse.error("更新商家失败: " + e.getMessage());
        }
    }

    /**
     * 删除商家
     */
    @DeleteMapping("/{id}")
    public ApiResponse<?> deleteMerchant(
        @PathVariable Integer id,
        @RequestHeader(value = "Authorization", required = false) String token
    ) {
        try {
            Merchant merchant = merchantService.findById(id);
            if (merchant == null) {
                return ApiResponse.error("商家不存在");
            }
            
            merchantService.deleteMerchant(id);
            return ApiResponse.success("商家删除成功");
        } catch (Exception e) {
            return ApiResponse.error("删除商家失败: " + e.getMessage());
        }
    }

    /**
     * 批量删除商家
     */
    @DeleteMapping("/batch")
    public ApiResponse<?> batchDeleteMerchants(
        @RequestBody Map<String, List<Integer>> request,
        @RequestHeader(value = "Authorization", required = false) String token
    ) {
        try {
            List<Integer> merchantIds = request.get("merchantIds");
            if (merchantIds == null || merchantIds.isEmpty()) {
                return ApiResponse.error("请选择要删除的商家");
            }
            
            int deletedCount = merchantService.batchDeleteMerchants(merchantIds);
            return ApiResponse.success("成功删除 " + deletedCount + " 个商家");
        } catch (Exception e) {
            return ApiResponse.error("批量删除商家失败: " + e.getMessage());
        }
    }

    /**
     * 更新商家审核状态
     */
    @PutMapping("/{id}/approval")
    public ApiResponse<?> updateApprovalStatus(
        @PathVariable Integer id,
        @RequestBody Map<String, Integer> request,
        @RequestHeader(value = "Authorization", required = false) String token
    ) {
        try {
            Integer isApproved = request.get("isApproved");
            if (isApproved == null || (isApproved != 0 && isApproved != 1 && isApproved != 2)) {
                return ApiResponse.error("审核状态值无效");
            }
            
            Merchant merchant = merchantService.findById(id);
            if (merchant == null) {
                return ApiResponse.error("商家不存在");
            }
            
            merchantService.updateApprovalStatus(id, isApproved);
            
            String statusText = "";
            switch (isApproved) {
                case 0: statusText = "待审核"; break;
                case 1: statusText = "审核通过"; break;
                case 2: statusText = "审核拒绝"; break;
            }
            
            return ApiResponse.success("商家状态已更新为：" + statusText);
        } catch (Exception e) {
            return ApiResponse.error("更新审核状态失败: " + e.getMessage());
        }
    }

    /**
     * 批量更新审核状态
     */
    @PutMapping("/batch/approval")
    public ApiResponse<?> batchUpdateApprovalStatus(
        @RequestBody Map<String, Object> request,
        @RequestHeader(value = "Authorization", required = false) String token
    ) {
        try {
            @SuppressWarnings("unchecked")
            List<Integer> merchantIds = (List<Integer>) request.get("merchantIds");
            Integer isApproved = (Integer) request.get("isApproved");
            
            if (merchantIds == null || merchantIds.isEmpty()) {
                return ApiResponse.error("请选择要操作的商家");
            }
            
            if (isApproved == null || (isApproved != 0 && isApproved != 1 && isApproved != 2)) {
                return ApiResponse.error("审核状态值无效");
            }
            
            int updatedCount = merchantService.batchUpdateApprovalStatus(merchantIds, isApproved);
            
            String statusText = "";
            switch (isApproved) {
                case 0: statusText = "待审核"; break;
                case 1: statusText = "审核通过"; break;
                case 2: statusText = "审核拒绝"; break;
            }
            
            return ApiResponse.success("成功将 " + updatedCount + " 个商家状态更新为：" + statusText);
        } catch (Exception e) {
            return ApiResponse.error("批量更新审核状态失败: " + e.getMessage());
        }
    }

    /**
     * 验证管理员token
     */
    private boolean validateAdminToken(String token) {
        try {
            if (token == null || !token.startsWith("Bearer ")) {
                return false;
            }
            
            String jwt = token.substring(7);
            String userType = jwtUtil.getUserTypeFromToken(jwt);
            return "admin".equals(userType);
        } catch (Exception e) {
            return false;
        }
    }


} 